package com.ssyt.ec.exam.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import com.ssyt.ec.common.Constant;
import com.ssyt.ec.common.util.DBUtil;
import com.ssyt.ec.exam.entity.PaperEntity;
import com.ssyt.ec.que.entity.QuestionEntity;

public class PaperService {
	/**
	 * 获取单题
	 * 
	 * @return
	 */
	public List<QuestionEntity> getSingleOption() {
		String sql = "SELECT id,question,answer_a,answer_b,answer_c,answer_d,answer FROM qes_qestions WHERE question_type=1 ORDER BY RAND() LIMIT ?; ";
		return DBUtil.executeQuery(QuestionEntity.class, sql,
				Constant.DEFAULT_SINGLE_OPTION_NUMBER);
	}

	/**
	 * 获取多选题
	 * 
	 * @return
	 */
	public List<QuestionEntity> getMultiOption() {
		String sql = "SELECT id,question,answer_a,answer_b,answer_c,answer_d,answer FROM qes_qestions WHERE question_type=2 ORDER BY RAND() LIMIT ?; ";
		return DBUtil.executeQuery(QuestionEntity.class, sql,
				Constant.DEFAULT_MULTI_OPTION_NUMBER);
	}

	/**
	 * 获取判断题
	 * 
	 * @return
	 */
	public List<QuestionEntity> getJudge() {
		String sql = "SELECT id,question,answer_a,answer_b,answer_c,answer_d,answer FROM qes_qestions WHERE question_type=3 ORDER BY RAND() LIMIT ?; ";
		return DBUtil.executeQuery(QuestionEntity.class, sql,
				Constant.DEFAULT_JUDGE_NUMBER);
	}

	/**
	 * 自动生成试卷
	 * 
	 * @return
	 */
	public long add(List<Object> paramList) {
		Connection connection = DBUtil.getConnection();
		String sql = "INSERT INTO qes_exam_paper VALUES (NULL,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,NOW(), ?, ?)";
		PreparedStatement preparedStatement = null;
		try {
			preparedStatement = connection.prepareStatement(sql,
					Statement.RETURN_GENERATED_KEYS);
			DBUtil.setParameter(paramList, preparedStatement);
			preparedStatement.executeUpdate();
			ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
			if (generatedKeys.next()) {
				return generatedKeys.getLong(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(preparedStatement, connection);
		}
		return 0;
	}

	/**
	 * 获取试卷信息
	 * 
	 * @param paperId
	 * @return
	 */
	public PaperEntity getPaperList(long paperId) {
		String sql = "SELECT q.*,c.name AS course_name FROM qes_exam_paper q,sys_course c WHERE q.id=? AND q.course_id=c.id";
		return DBUtil.getUniqueResult(PaperEntity.class, sql, paperId);
	}

	/**
	 * 添加考试记录
	 * 
	 * @param paramList
	 * @return
	 */
	public int addRecords(List<Object> paramList) {
		String sql = "INSERT INTO exam_records VALUES(NULL,?,?,?,NOW(),?,?);";
		return DBUtil.executeUpdate(sql, paramList);
	}
}
